app.controller('addCookCtrl',['$scope', '$location', '$filter', 'CookApi', '$q', 'FileUploader','sweetAlertUtil', 'datepickerPopupConfig', 'datepickerConfig',
	function($scope, $location, $filter, CookApi, $q, FileUploader,sweetAlertUtil,datepickerPopupConfig, datepickerConfig){
	initDatePicker()
    function initDatePicker() {
        datepickerConfig.minMode = "day"
        datepickerConfig.datepickerMode="day"
        datepickerConfig.showWeeks = false;
        datepickerPopupConfig.showButtonBar = false
    }
	$scope.coId = $location.search().co_id;

	function getRoleInfo(){
		var defer = $q.defer();
		CookApi.getRoleInfo().then(function(res){
			if(res.code == 200){
				defer.resolve(res.result);
			}else{
				defer.reject(res.msg);
			}
		});
		return defer.promise;
	}
	$scope.areaList = [];
	// 编辑显示
	if ($scope.coId) {
		CookApi.cookInfo($scope.coId).then(function(res){
			if(res.code == 200) {
				$scope.cook = res.result;
				$scope.city_info = res.result.city_info;
				CookApi.getAreas().then(function(res){
					if(res.code == 200) {
						$scope.areaList = res.result.citys;
						$scope.areaList.forEach(function(item){
							CookApi.loadCitys(item.city_id).then(function(result){
								if(result.code == 200){
									item['sub_area'] = result.result.list;
									item['sub_area'].forEach(function(subArea){
										$scope.city_info.forEach(function(cinfo){
											if(subArea.city_id == cinfo.city_id){
												subArea.checked = true;
											}
										})
									})
								}
							})
						})
					}
				})
			}
		})
	}else {
		CookApi.getAreas().then(function(res){
			if(res.code == 200) {
				$scope.areaList = res.result.citys
				$scope.areaList.forEach(function(item){
					CookApi.loadCitys(item.city_id).then(function(result){
						if(result.code == 200){
							item['sub_area'] = result.result.list;
						}
					})
				})
			}
		})
	}
	$scope.checkAll = function(area){
		area.sub_area.forEach(function(subArea){
			if (area.checked) {
				subArea['checked'] = true;
			}else{
				subArea['checked'] = false;
			}
		});
	}

	$scope.cook = {
		co_username: '',
		co_phone: '',
		co_idcard: '',
		co_gender: 'MAN',
		co_num: '',
		send_papers_date: '',
		co_validity_period: '',
		co_contact_addr: '',
		city_ids: [],
		co_mark: '',
		co_auth_status: 'Y',
		co_rank: 'SUPER',
		co_id: '',
		co_pic: ''
	}

	$scope.submit = function($event){
		$scope.saveData = {
			co_username: $scope.cook.co_username,
			co_phone: $scope.cook.co_phone,
			co_idcard: $scope.cook.co_idcard,
			co_gender: $scope.cook.co_gender,
			co_num: $scope.cook.co_num,
			send_papers_date: $filter('date')($scope.cook.send_papers_date,'yyyy-MM-dd'),
			co_validity_period: $scope.cook.co_validity_period,
			co_contact_addr: $scope.cook.co_contact_addr,
			city_ids: $scope.cook.city_ids,
			co_mark: $scope.cook.co_mark,
			co_auth_status: $scope.cook.co_auth_status,
			co_rank: $scope.cook.co_rank,
			co_id: $scope.cook.co_id,
			co_pic: $scope.cook.co_pic
		}
		$scope.filterArea();
		if($scope.saveData.co_username==''){
			sweetAlertUtil.fail('厨师姓名不能为空！');
			return;
		}
		if($scope.saveData.co_phone==''){
			sweetAlertUtil.fail('联系电话不能为空！');
			return;
		}
		if($scope.saveData.co_idcard==''){
			sweetAlertUtil.fail('身份证号不能为空！');
			return;
		}
		if($scope.saveData.co_num==''){
			sweetAlertUtil.fail('厨师证号不能为空！');
			return;
		}
		if($scope.saveData.co_contact_addr==''){
			sweetAlertUtil.fail('联系地址不能为空！');
			return;
		}
		if($scope.saveData.city_ids.length == 0){
			sweetAlertUtil.fail('请选择服务区域！');
			return;
		}
		if($scope.saveData.co_pic == ''){
			sweetAlertUtil.fail('请上传头像！');
			return;
		}
		$($event.target).attr('disabled','disabled');
		if($scope.coId) {
			CookApi.updateCook($scope.coId,$scope.saveData).then(function(res){
				$($event.target).removeAttr('disabled');
				if(res.code == 200){
					window.location.href = "#/app/cooks/list";
				}else{
					sweetAlertUtil.fail(res.msg);
				}
			}, function(){
				sweetAlertUtil.fail('服务器异常');
				$($event.target).removeAttr('disabled');
			})
		}else{
			CookApi.storeCook($scope.saveData).then(function(res){
				$($event.target).removeAttr('disabled');
				if(res.code == 200){
					window.location.href = "#/app/cooks/list";
				}else {
					sweetAlertUtil.fail(res.msg);
				}
			});
		}
	}
	$scope.filterArea = function(){
		$scope.saveData.city_ids = [];
		$scope.areaList.forEach(function(item){
			item.sub_area.forEach(function(subItem){
				if(subItem.checked){
					$scope.saveData.city_ids.push(subItem.city_id);
				}
			})
		})
	}

    // 上传图片
	$scope.uploaderCoverImage = new FileUploader({
        url: "/api/file/upload",
        alias: "fileInfo",
        queueLimit: 1,
        autoUpload: true
    });
    $scope.uploaderCoverImage.filters.push({
        name: 'imageFilter',
        fn: function(item /*{File|FileLikeObject}*/ , options) {
            var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
            return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
        }
    });
    $scope.uploaderCoverImage.onSuccessItem = function(fileItem, response, status, headers) {
    	$scope.cook.co_pic = response.result.at_id ;
        $scope.cook.pic_url = response.result.path ;
    };
    //删除图片
    $scope.removeCover = function () {
        var item = $scope.uploaderCoverImage.queue[0];
        if(item){    
            if (item.isUploading) item.cancel();

            $scope.uploaderCoverImage.queue.splice(0, 1);

            item._destroy();

            $scope.uploaderCoverImage.progress = $scope.uploaderCoverImage._getTotalProgress();
        }
        $scope.cook.co_pic = null ;
        $scope.cook.pic_url = null ;
    };
}])